package com.example.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;

public class OrderTableCreator {
    public static void main(String[] args) {
        createOrdersTable();
    }
    
    public static void createOrdersTable() {
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement()) {
            
            // 创建订单表
            String createTableSQL = 
              "CREATE TABLE IF NOT EXISTS orders (" +
             "id INT PRIMARY KEY AUTO_INCREMENT," +
              "user_id INT NOT NULL," +
              "book_id INT NOT NULL," +
               "quantity INT NOT NULL DEFAULT 1," +
              "total_price DECIMAL(10,2)," +
              "order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP," +
                "status VARCHAR(20) DEFAULT 'pending'," +
               "shipping_address VARCHAR(255)," +
            "contact_phone VARCHAR(20)," +
             "notes TEXT" +
                ")";      
            stmt.executeUpdate(createTableSQL);
            System.out.println("✅ 订单表创建成功");
            
            // 确保books表有price和stock字段
            try {
                stmt.executeUpdate("ALTER TABLE books ADD COLUMN price DECIMAL(10,2) NOT NULL DEFAULT 29.9");
                System.out.println("✅ 为books表添加price字段");
            } catch (Exception e) {
                System.out.println("ℹ️books表已有price字段");
            }
            
            try {
                stmt.executeUpdate("ALTER TABLE books ADD COLUMN stock INT DEFAULT 10");
                System.out.println("✅ 为books表添加stock字段");
            } catch (Exception e) {
                System.out.println("ℹ️books表已有stock字段");
            }
            
            // 插入示例订单数据
            String insertSQL = 
          "INSERT INTO orders (user_id, book_id, quantity, total_price, status, shipping_address, contact_phone) VALUES " +
               "(1, 1, 2,5980completed', '北京市朝阳区某某街道123', '13800138001')," +
               "(1, 2, 129.90 pending', '北京市朝阳区某某街道123', '13800138001')," +
               "(2, 3, 1,3990completed', '上海市浦东新区某某路456', '13800138002')," +
               "(2, 1, 129.90pending', '上海市浦东新区某某路456', '13800138002')";      
            stmt.executeUpdate(insertSQL);
            System.out.println("✅ 示例订单数据插入成功");
            
            // 更新图书价格和库存
            stmt.executeUpdate("UPDATE books SET price =29.9, stock = 100 WHERE price IS NULL");
            stmt.executeUpdate("UPDATE books SET price = 39.9, stock = 50 WHERE price = 29.9");
            stmt.executeUpdate("UPDATE books SET price = 49.9, stock = 30 WHERE price = 39.9");
            System.out.println("✅ 图书价格和库存更新成功");
            
            System.out.println("🎉 订单表初始化完成！");
            
        } catch (Exception e) {
            System.err.println("❌ 创建订单表失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 